<template>
  <a-tree
    class="division-tree"
    :show-line="true"
    v-model:expandedKeys="expandedKeys"
    v-model:selectedKeys="selectedKeys"
    @select="select"
    @expand="expand"
    :loadedKeys="loadedKeys"
    :loadData="onLoadData"
    :loading="loading"
    @load="loadFinish"
    :tree-data="treeData"
    :autoExpandParent="true"
  />
</template>

<script>
import { divisonApi } from '@/api/core/division';

export default {
  name: 'DivisionTree',
  data () {
    return {
      selectedKeys: [],
      expandedKeys: [],
      loadedKeys: [],
      currentNode: null, // 当前被选中的节点
      nodes: [], // 选中的节点层级
      treeData: [{title: '行政区划', key: '0', isLeaf: false, level: 0}],
      loading: false
    }
  },
  methods: {
    // 节点开始异步加载触发方法
    onLoadData (treeNode) {
      const that = this
      return new Promise(resolve => {
        divisonApi.getListTreeByPid({
          pid: treeNode.key
        }).then((res) => {
          if (res.code === 1000) {
            if (res.data.length === 0)  {
              resolve();
              return;
            }
            treeNode.dataRef.children = res.data.map((item) => {
              return item
            })
            that.treeData = [...that.treeData];
            resolve();
          }
        })
      });
    },
    // 节点加载完毕后触发方法
    loadFinish(loadedKeys,{event,node}) {
      this.loadedKeys = loadedKeys
    },
    // 节点选中方法
    select(selectedKeys, event) {
      this.currentNode = event.selected ? event.node : null
      if (this.currentNode) {
        if (this.currentNode.parent) {
          // 获取节点层级的key值集合
          this.nodes = this.currentNode.parent.nodes.map((item) => {
            return item.key
          })
          this.nodes.push(this.currentNode.key)
        } else {
          this.nodes = [this.currentNode.key]
        }
      }
      this.$emit('selectChange',this.currentNode)
    },
    // 节点展开方法
    expand(expandedKeys, {expanded, node}) {
      if (!expanded) {
        node.dataRef.children = []
        this.treeData = [...this.treeData]
        this.loadedKeys = this.loadedKeys.filter((item) => item !== node.key)
      }
      this.$emit('expandChange',this.expandedKeys)
    },
    /**
     * 刷新方法, node是树节点，刷新该节点
     * @param type 刷新类型，1新增，2删除，3编辑
     * @param resNodes 处理的节点
     */
    refresh (type, resNodes) {
      this.loading = true
      if (this.currentNode) {
        this.expandedKeys = this.expandedKeys.filter((item) => item !== this.currentNode.key)
        this.loadedKeys = this.loadedKeys.filter((item) => item !== this.currentNode.key)
        const len = this.nodes.length
        let array = this.treeData
        for (let i = 0; i < len; i++) {
          const itemByKey = this.getItemByKey(array, this.nodes[i]);
          array = itemByKey.item.children
          if (i === len - 1) {
            itemByKey.item.isLeaf = false
          }
        }
        // 如果是编辑刷新
        if (type === 3) {
          const len1 = resNodes.length
          array = this.treeData
          for (let i = 0; i < len1; i++) {
            const itemByKey = this.getItemByKey(array, resNodes[i]);
            array = itemByKey.item.children
            if (i === len - 1) {
              itemByKey.item.isLeaf = false
            }
          }
        }
      } else {
        // 最外层节点是否展开
        if (this.expandedKeys.includes('0')) {
          this.expandedKeys = []
          this.loadedKeys = []
        }
      }
    },
    /**
     * 根据key值在节点集合中拿取节点
     * @param array 节点集合
     * @param key
     */
    getItemByKey (array, key) {
      const len = array.length
      for (let i = 0; i < len; i++) {
        const item = array[i]
        if (item.key === key) {
          return {
            item: item,
            index: i
          }
        }
      }
    },
    /**
     * 增加节点的递归方法
     * @param array 当前一层的节点数据集合
     * @param key 当前一层节点集合中需要寻找的key，根据key查找到节点
     * @param level 需要寻找的节点层级
     * @param index 当前的节点层级
     * @param node 需要添加的节点
     */
    addNodes (array, key, level, index, node) {
      array.forEach(item => {
        if (item.key === key) {
          if (level === index) {
            item.children = [...item.children, node]
          } else {
            this.addNodes(item.children, )
          }
        }
      })
    },
  }
};
</script>

<style lang="less" scoped>
  :deep(.division-tree){
    width: 100%;
    overflow: auto;
    .ant-tree .ant-tree-treenode{
      width: 100%;
    }
  }
</style>
